<?php
namespace app\small\controller;
use app\common\base\_Db;
use think\Config;
use think\Db;
use think\Exception;
use think\Loader;
use think\Log;
use vehicle\signvehicle;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/23
 * Time: 9:36
 */
class Pay{
    //申请签约
    public function entrustweb(){
        $uid = input('uid');
        $result = _Db::GetData('user',array('user_id'=>'uid','openid'=>'openid','sign_contract_id'=>'sign_contract_id','contract_code'=>'contract_code'),'user_id = '.$uid);
        $url ='https://api.mch.weixin.qq.com/papay/partner/entrustweb';
        $data = [
            'mch_id'                  => pay_config()['mch_id'], // 服务商商户号
            'appid'                   => pay_config()['appid'],   //服务商商户号绑定的APPID
            'sub_mch_id'              => pay_config()['sub_mch_id'], //子商户号
            'sub_appid'               => pay_config()['sub_appid'], //子商户号
            'plan_id'                 => pay_config()['plan_id'],  //商户模板ID
            'contract_code'           => date('YmdHis',time()).rand(0000,9999), //签约协议号 年月日
            'request_serial'          => 1000,  //1000商户请求签约时的序列号，商户侧须唯一。序列号主要用于排序，不作为查询条件，纯数字。长度不超过12位   长度
            'contract_display_account'=> '乘车码', //签约用户的名称，用于页面展示，参数值不支持UTF8非3字节编码的字符，例如表情符号，所以请勿传微信昵称到该字段
            'notify_url'              =>  pay_config()['notify_url'],  //用于接收签约成功消息的回调通知地址，以http或https开头。请对notify_url参数值进行encode处理。当签约场景为APP时，且系统为ios时，需要对参数值encode两次
            'timestamp'               => time(),
        ];
        $method = 'MD5'; //通过md5方式签名
        //商户key
        $paran = signvehicle::sign($data,'AF7M2HpBiYpibtXGy7RpBm3pTZGr9rzf',$method);
        if (!empty($result['sign_contract_id']&&$result['contract_code'])){
            return json_encode('授权失败');
        }else{
            Db::table('user')->where('openid = "'.$result['openid'].'"')->update(array('contract_code'=>$data['contract_code']));
        }
        return json_encode($paran);
        //公众号
        //$paran = signvehicle::ToUrlParams($paran);//拼接成字串
        //$server_url = $url . '?' . $paran;
        //dump($server_url);
    }

    //BUG申请扣费
    public function payapply(){
        $uid = input('uid');
        $iden = input('iden');
        /*if ($iden == 1){*/
        $result = _Db::GetData('user',array('user_id'=>'uid','openid'=>'openid','sign_contract_id'=>'sign_contract_id'),'user_id = '.$uid);
        $url = 'https://api.mch.weixin.qq.com/transit/partnerpay/payapply';
        $scene_info=[
            'start_time'=>date('YmdHis'),  //扣费时间
        ];
        $re = json_encode(['scene_info'=>$scene_info],JSON_UNESCAPED_UNICODE);
        $post_data = [
            'appid'         => pay_config()['appid'],   //服务商商户号绑定的APPID
            'mch_id'        => pay_config()['mch_id'], // 服务商商户号
            'sub_mch_id'    => pay_config()['sub_mch_id'], //子商户号
            'nonce_str'     =>'5K8264ILTKCHCQ5011SI8ZNMTM67VS', //
            'sign_type'     =>'HMAC-SHA256', //签名类型
            'body'          =>'公交代扣',  //商品描述
            'out_trade_no'  =>rand(10000,99999),  //订单号
            'total_fee'     =>1,  //金额
            'spbill_create_ip'=>'127.0.0.1', //终端IP
            'notify_url'    =>HttpPath.'/small/Pay/backNotify', //回调通知url
            'trade_type'    =>'PAP', //交易类型
            'contract_id'   =>$result['sign_contract_id'], //扣费协议号201810225891807497
            'trade_scene'   =>'BUS', //场景信息
            'scene_info'    =>json_encode(['scene_info'=>$scene_info],JSON_UNESCAPED_UNICODE),
        ];
        $method = 'HMAC-SHA256'; //通过md5方式签名
        $post_data = signvehicle::sign($post_data,'AF7M2HpBiYpibtXGy7RpBm3pTZGr9rzf',$method);
        $curlPost = signvehicle::build($post_data);
        $data = signvehicle::curl_post($url,$curlPost);
        $res =signvehicle::toArray($data);
        dump($res);
    }
    //扣费回调地址
    public function backNotify(){
        $xml=file_get_contents('php://input', 'r');
        //  Log::write(json_encode($xml,JSON_UNESCAPED_UNICODE),'error');
        $data = signvehicle::toArray($xml);
    }
    //BUG签约回调
    public function notify(){
        $xml=file_get_contents('php://input', 'r');
        //  Log::write(json_encode($xml,JSON_UNESCAPED_UNICODE),'error');
        $data = signvehicle::toArray($xml);
        $data_sign=$data['sign'];
        unset($data['sign']);
        $sign= signvehicle::sign($data,'AF7M2HpBiYpibtXGy7RpBm3pTZGr9rzf','MD5');
        if($sign["sign"]===$data_sign and $data['return_code']=='SUCCESS' and $data['result_code']=='SUCCESS'){
            $result=true;
            $contract_id = $data['contract_id'];
            $contract_code = $data['contract_code'];
            $openid = $data['sub_openid'];
            $res = _Db::GetData('user','contract_code','openid= "'.$data['sub_openid'].'"');
            if (!empty($res['contract_code'])&&($res['contract_code'] == $data['contract_code'])){
                Db::table('user')->where('openid = "'.$openid.'"')->update(array('sign_contract_id'=>$contract_id,'contract_code'=>$contract_code));
            }
        }else{
            $result=false;
        }
        if($result){
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;

    }

    public function xml(){
        $arr = array(
            "return_code" => "SUCCESS",
            "return_msg" => "OK",
            "appid" => "wxa428801b2e7170b1",
            "mch_id" => "1508509181",
            "nonce_str" => "iCEJpRsjAEkgk7TC8cyyBrNzFOEJFMEG",
            "sign" => "4259C1248E14912D4DB1FED1385326A5E45F5065CD222E01539AD29B8EBD109A",
            "result_code" => "SUCCESS",
            "user_state" => "NORMAL",
            "contract_id" => "201810235105659653",
            "plan_id" => "122654",
            "contract_code" => "47713",
            "contract_state" => "0",
            "sub_mch_id" => "1512890131",
        );
    }


    //签约验证
//    public function querystate(){
//        $uid = input('uid');
//        $iden = input('iden');
//        /*if ($iden == 1){*/
//            $result = _Db::GetData('user',array('user_id'=>'uid','openid'=>'openid','sign_contract_id'=>'sign_contract_id'),'user_id = '.$uid);
//
//            $openid = $result['openid'];
//            $contract_id = $result['sign_contract_id'];
//            $url = 'https://api.mch.weixin.qq.com/transit/partnerpay/querystate';
//            $post_data = [
//                'appid'        => pay_config()['appid'],   //服务商商户号绑定的APPID
//                'mch_id'       => pay_config()['mch_id'], // 服务商商户号
//                'sub_mch_id'   => pay_config()['sub_mch_id'], //子商户号
//                'nonce_str'     =>'5K8264ILTKCHCQ5011SI8ZNMTM67VS', //
//                'contract_id'   =>$contract_id, //扣费协议号201810235105659653
//                'sign_type'     =>'HMAC-SHA256', //签名类型
//                'openid'        =>$openid, //子商户openid opnEf5ZdqI-5TB4dwrwTRc2YiKJs
//            ];
//            $method = 'HMAC-SHA256'; //通过md5方式签名
//            $post_data = signvehicle::sign($post_data,'AF7M2HpBiYpibtXGy7RpBm3pTZGr9rzf',$method);
//            $curlPost = signvehicle::build($post_data);
//            $data = signvehicle::curl_post($url,$curlPost);
//            $res =signvehicle::toArray($data);
//            return json_encode($res);
//        /*}else{
//            return 0;
//        }*/
//    }
    //验证数据库是否有签约协议号
    public function Contract(){
        $uid = input('uid');
        $iden = input('iden');
        $res = _Db::GetData('user','sign_contract_id,contract_code,openid','user_id = '.$uid);
        if ($iden == 1){
            if (empty($res['sign_contract_id']&&$res['contract_code'])){
                return 'false';
            }else{
                return 'true';
            }
        }elseif ($iden == 2){
            //机场职工
            $table_name='staff';
            $field = array('staff_id'=>'uid','regist'=>'regist','openid'=>'openid');
            if (empty($res)){
                //uid非user表id
                $res_staff = _Db::GetData($table_name,$field,'staff_id = '.$uid);
            }else{
                $res_staff = _Db::GetData($table_name,$field,'openid = "'.$res['openid'].'"');
            }
            $result = _Db::GetData('user','sign_contract_id,contract_code','openid = "'.$res_staff['openid'].'"');
            if ($res_staff['regist'] != 3 ){
                //员工在未审核通过状态
                if (empty($result['sign_contract_id']&&$result['contract_code'])){
                    return 'false';
                }else{
                    return 'true';
                }
            }
        }elseif ($iden == 3){
            //驻场职工
            $table_name='external_staff';
            $field = array('id'=>'uid','regist'=>'regist','openid'=>'openid');
            if (empty($res)){
                //uid非user表id
                $res_exter = _Db::GetData($table_name,$field,'id = '.$uid);
            }else{
                $res_exter = _Db::GetData($table_name,$field,'openid = "'.$res['openid'].'"');
            }
            $result = _Db::GetData('user','sign_contract_id,contract_code','openid = "'.$res_exter['openid'].'"');
            if ($res_exter['regist'] != 3 ){
                //员工在未审核通过状态
                if (empty($result['sign_contract_id']&&$result['contract_code'])){
                    return 'false';
                }else{
                    return 'true';
                }
            }
        }
    }

    //验证是否解密
    public function deletecontract(){
        $xml=file_get_contents('php://input','r');
        $data=signvehicle::toArray($xml);
        $data_sign=$data['sign'];
        unset($data['sign']);
        $sign= signvehicle::sign($data,'AF7M2HpBiYpibtXGy7RpBm3pTZGr9rzf','MD5');
        if($sign["sign"]===$data_sign and $data['return_code']=='SUCCESS' and $data['result_code']=='SUCCESS'){
            $result=true;
            Log::write($data,'info');
            $res = _Db::GetData('user','sign_contract_id,contract_code','openid= "'.$data['sub_openid'].'"');
            if (!empty($res['sign_contract_id']) && ($res['contract_code'] == $data['contract_code'])){
                Db::table('user')->where('openid= "'.$data['sub_openid'].'"')->update(array('sign_contract_id'=>'','contract_code'=>''));
            }
        }else{
            $result=false;
        }
        if($result){
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
    }
}